<template>
  <div id="DealOrder">
    <span v-if="whichTab">
      <span>
        <slot v-if="whichTab === '待发货' || whichTab === '已完成'">
          <el-button
            type="text" size="small" plain
            @click="lookDetail(item)">
            查看详情
          </el-button>
        </slot>

        <slot v-if="whichTab === '待发货'">
          <el-button
            v-if="item.saleItemType === 0 && item.logisticsId !== 1"
            type="text" size="small" @click="deliverGoods(item)">
            发货
          </el-button>
          <el-button
            v-if="(item.saleItemType === 0 || item.saleItemType === 2) && item.logisticsId === 1"
            type="text" size="small" @click="confirmOneself(item)">
            确认自提
          </el-button>
          <el-button
            v-if="item.saleItemType === 1"
            type="text" size="small" @click="confirmDoctor(item)">
            确认就医
          </el-button>
          <el-button
            v-if="item.saleOrderDetailList[0].quantity > 1"
            type="text" size="small" @click="timesToConfirmClick(item)">
            分批确认
          </el-button>
        </slot>

        <slot v-if="whichTab === '退款' && item.state === 0">
          <el-button
            type="text" size="small"
            @click="refundYesClick(item)">
            同意退款
          </el-button>
          <el-button
            type="text" size="small"
            @click="refundNoClick(item)"
            style="color: #dd6161">
            拒绝退款
          </el-button>
        </slot>

        <slot v-if="whichTab === '已付款'">
          <el-button
            v-if="item.saleItemType === 0 && item.logisticsId !== 1"
            type="text" size="small"
            @click="auditHasPay(item)">
            审核
          </el-button>
        </slot>
      </span>
    </span>

    <span v-if="detailFlag"> <!-- 详情页面所要展示的 -->
      <span v-if="detailFlag === '待发货'">
        <el-button
          v-if="item.saleItemType === 0 && item.logisticsId !== 1"
          type="primary"
          @click="deliverGoods(item)">
          发货
        </el-button>
      </span>
      <span v-if="detailFlag === '待就医'">
        <el-button
          v-if="item.saleItemType === 1"
          type="primary"
          @click="confirmDoctor(item)">
          确认就医
        </el-button>
      </span>
      <span v-if="detailFlag === '待自提'">
        <el-button
          v-if="(item.saleItemType === 0 || item.saleItemType === 2) && item.logisticsId === 1"
          type="primary"
          @click="confirmOneself(item)">
          确认自提
        </el-button>
      </span>
      <span v-if="detailFlag === '已发货'">
        <div class="order_baseInfo">
          <div>
            <span>物流公司：</span>
            <span v-if="needShowInfo">{{needShowInfo.logisticsName}}</span>
            <span v-else>{{item.logistics}}</span>
          </div>
          <div>
            <span>运单号：</span>
            <span v-if="needShowInfo">{{needShowInfo.logisticsOrderNo}}</span>
            <span v-else>{{item.logistics}}</span>
            <!-- <el-button
              type="text" size="small"
              style="color: #D6B45B">
              查看运单号
            </el-button> -->
          </div>
        </div>
      </span>
      <span v-if="detailFlag === '已就医'">
        <div class="order_baseInfo">
          <div>
            <span>就医人：</span>
            <span v-if="needShowInfo">{{needShowInfo.pickName}}</span>
            <span v-else>{{item.pickName}}</span>
          </div>
          <div>
            <span>手机号：</span>
            <span v-if="needShowInfo">{{needShowInfo.pickPhoneNumber}}</span>
            <span v-else>{{item.pickPhoneNumber}}</span>
          </div>
          <div>
            <span>就医时间：</span>
            <span v-if="needShowInfo">{{needShowInfo.pickTime}}</span>
            <span v-else>{{item.pickTime}}</span>
          </div>
        </div>
      </span>
      <span v-if="detailFlag === '已自提'">
        <div class="order_baseInfo">
          <div>
            <span>自提人：</span>
            <span v-if="needShowInfo">{{needShowInfo.pickName}}</span>
            <span v-else>{{item.pickName}}</span>
          </div>
          <div>
            <span>手机号：</span>
            <span v-if="needShowInfo">{{needShowInfo.pickPhoneNumber}}</span>
            <span v-else>{{item.pickPhoneNumber}}</span>
          </div>
          <div>
            <span>自提时间：</span>
            <span v-if="needShowInfo">{{needShowInfo.pickTime}}</span>
            <span v-else>{{item.pickTime}}</span>
          </div>
        </div>
      </span>
    </span>

    <!-- 发货dialog -->
    <el-dialog
      title="发货"
      :visible.sync="deliverGoodsVisible"
      :before-close="done => { resetForm('deliverForm'); done() }">
      <el-form
        :model="deliverForm" :rules="deliverFormRules"
        ref="deliverForm" label-width="100px">
        <el-form-item label="收件人">
          {{ deliverForm.recipient }}
        </el-form-item>
        <el-form-item label="手机号">
          {{ deliverForm.phone }}
        </el-form-item>
        <el-form-item label="收货地址">
          {{ deliverForm.address }}
        </el-form-item>
        <el-form-item label="物流公司">
          {{ deliverForm.logisticsName }}
        </el-form-item>
        <el-form-item label="运单号" prop="logisticsOrderNo">
          <el-input :disabled="deliverOkLoading" v-model="deliverForm.logisticsOrderNo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => { deliverGoodsVisible = false; resetForm('deliverForm') }">取 消</el-button>
        <el-button type="primary" @click="deliverDialogOk()" :loading="deliverOkLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 确认就医 or 自提 -->
    <el-dialog
      :title="`确认${doctorOrRecipientTitle}`"
      :visible.sync="doctorOrPickVis"
      :before-close="done => { resetForm('doctorOrPickForm'); done() }">
      <el-form
        :model="doctorOrPickForm" :rules="doctorOrPickFormRules"
        ref="doctorOrPickForm" label-width="100px">
        <el-form-item :label="`${doctorOrRecipientTitle}人`" prop="pickName">
          <el-input
            :disabled="docOrPickOkLoading"
            v-model="doctorOrPickForm.pickName"
            :placeholder="`请输入${doctorOrRecipientTitle}人`"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="pickPhoneNumber">
          <el-input
            :disabled="docOrPickOkLoading"
            v-model="doctorOrPickForm.pickPhoneNumber"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item :label="`${doctorOrRecipientTitle}时间`" prop="pickTime_mapping">
          <el-date-picker
            :disabled="docOrPickOkLoading"
            v-model="doctorOrPickForm.pickTime_mapping"
            type="datetime">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => { doctorOrPickVis = false; resetForm('doctorOrPickForm') }">取 消</el-button>
        <el-button type="primary" @click="confirmDocOrPickOk('doctorOrPickForm')" :loading="docOrPickOkLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分批确认 -->
    <el-dialog
      title="分批确认"
      :visible.sync="timesToConfirmVis"
      width="80%"
      :before-close="done => { resetForm('timesToConfirmForm'); done() }">
      <span style="font-weight: 600;">已分批确认记录：</span>
      <el-table
        v-if="item.childSaleOrderList"
        :data="item.childSaleOrderList"
        border
        style="width: 100%; margin-bottom: 20px;">
        <el-table-column
          prop="ordername"
          label="商品名称">
        </el-table-column>
        <el-table-column
          prop="saleOrderDetailList[0].specName"
          label="规格">
        </el-table-column>
        <el-table-column
          prop="saleOrderDetailList[0].quantity"
          label="确认数量">
        </el-table-column>
        <el-table-column
          prop="createdate"
          label="确认时间">
        </el-table-column>
        <el-table-column
          prop="remarksShop"
          label="备注">
        </el-table-column>
      </el-table>
      <span style="font-weight: 600;">本次确认：</span>
      <el-form
        :model="timesToConfirmForm" :rules="timesToConfirmFormRules"
        ref="timesToConfirmForm" label-width="100px">
        <el-form-item label="规格" prop="itemSpecId">
          <el-select
            v-model="timesToConfirmForm.itemSpecId" placeholder="请选择规格"
            :disabled="timesToConfirmLoading">
            <el-option
              v-for="item in timesToConfirmSpec" :key="item.id"
              :label="item.specName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="确认数量" prop="quantity">
          <span>订单总数量：</span>
          <span v-if="timesToConfirmSpec">{{timesToConfirmSpec[0].orderCount}}</span>
          <span style="margin-left: 20px;">剩余数量：</span>
          <span v-if="timesToConfirmSpec" style="color: #1a9efb;">{{timesToConfirmSpec[0].residualCount}}</span>
          <el-input
            :disabled="timesToConfirmLoading"
            v-model.number="timesToConfirmForm.quantity"
            placeholder="请输入本次确认数量"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            :disabled="timesToConfirmLoading"
            v-model="timesToConfirmForm.remarksShop"
            placeholder="请输入备注"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => { timesToConfirmVis = false; resetForm('timesToConfirmForm') }">取 消</el-button>
        <el-button type="primary" @click="timesToConfirmOk('timesToConfirmForm')" :loading="timesToConfirmLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 同意退款 -->
    <el-dialog
      title="退款"
      :visible.sync="refundDiaVis">
      <el-form
        :model="refundOkForm"
        ref="refundOkForm" label-width="100px"
        :rules="refundOkFormRules">
        <el-form-item label="退款金额" prop="amount">
          <el-input
            :disabled="refundDiaOkLoading"
            v-model="refundOkForm.amount"
            style="width: 220px">
          </el-input>
          <div>应退金额： ￥<span v-text="refundOkForm.totalprice"></span></div>
        </el-form-item>
        <el-form-item>
          同意退款后，相应的积分会收回，相应的券也会退回
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => { resetForm('refundOkForm'); refundDiaVis = false }">取 消</el-button>
        <el-button
          type="primary" @click="refundDiaOk('refundOkForm')"
          :loading="refundDiaOkLoading">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import moment from 'moment'
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'
export default {
  name: 'DealOrder',
  props: [ 'item', 'whichTab', 'state', 'detailFlag' ],
  components: {},
  mounted () {
    this.$nextTick(() => this.init())
  },
  data () {
    const validateLogisticsOrderNo = (rule, value, callback) => { // 校验运单号
      if (!value) {
        return callback(new Error('运单号不能为空'))
      }
      let regNum = /^[0-9]*$/
      if (!regNum.test(value)) {
        return callback(new Error('运单号只能是数字'))
      }
      callback()
    }

    const validatePhoneNum = (rule, value, callback) => { // 校验手机号
      if (!value) {
        return callback(new Error('请输入手机号'))
      }
      let regNum = /^1[0-9]{10}$/
      if (!regNum.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      }
      callback()
    }

    const validateQuantity = (rule, value, callback) => { // 校验分批确认数量
      if (!value) {
        return callback(new Error('请输入确认数量'))
      }
      let regNum = /^[1-9]\d*$/
      if (!regNum.test(value)) {
        return callback(new Error('请输入正确的数值'))
      }
      if (value > this.timesToConfirmSpec[0].residualCount) {
        return callback(new Error('不能大于订单剩余数量'))
      }
      callback()
    }

    const validateRefundInput = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('退款金额不能为空'))
      }
      setTimeout(() => {
        if (!isNaN(value)) {
          if (value <= 0) {
            callback(new Error('请输入大于0的数值'))
          } else if (value > this.refundOkForm.totalprice) {
            callback(new Error(`输入的数值不能大于${this.refundOkForm.totalprice}`))
          } else {
            callback()
          }
        } else {
          callback(new Error('请输入正确的数值'))
        }
      }, 100)
    }

    return {
      doctorOrRecipientTitle: '', // 就医或者自提的dialog title
      doctorOrPickVis: false,
      docOrPickOkLoading: false,
      doctorOrPickFormRules: {
        pickName: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        pickPhoneNumber: [
          { required: true, validator: validatePhoneNum, trigger: 'blur' }
        ],
        pickTime_mapping: [
          { required: true, message: '该项不能为空', trigger: 'change' }
        ]
      },
      doctorOrPickForm: { // 确认就医或确认自提dialog上的表单数据
        orderId: null,
        pickName: '',
        pickPhoneNumber: '',
        pickTime: '',
        pickTime_mapping: ''
      },
      deliverOkLoading: false,
      timesToConfirmVis: false,
      timesToConfirmLoading: false,
      timesToConfirmFormRules: {
        itemSpecId: [
          { required: true, message: '请选择规格', trigger: 'change' }
        ],
        quantity: [
          { required: true, validator: validateQuantity, trigger: 'blur' }
        ]
      },
      timesToConfirmForm: {
        orderId: '',
        itemSpecId: '',
        quantity: '',
        remarksShop: ''
      },
      timesToConfirmSpec: null, // 分批确认的规格
      deliverGoodsVisible: false, // 发货Dialog框控制器
      deliverFormRules: {
        logisticsOrderNo: [
          { required: true, validator: validateLogisticsOrderNo, trigger: 'blur' }
        ]
      },
      deliverForm: { // 发货表单数据
        logisticsOrderNo: '', // 运单号
        recipient: '', // 收件人
        logisticsName: '', // 快递
        address: '', // 地址
        phone: '', // 电话
        orderId: '' // 订单编号
      },
      beHandlingRow: null,
      refundDiaVis: false,
      refundOkFormRules: {
        amount: [
          { validator: validateRefundInput, trigger: 'blur' }
        ]
      },
      refundOkForm: {
        id: null,
        saleRefundId: null,
        amount: null,
        totalprice: null
      },
      needShowInfo: null,
      refundDiaOkLoading: false
    }
  },
  watch: {
    'doctorOrPickForm.pickTime_mapping' (val, oldVal) {
      this.doctorOrPickForm.pickTime = moment(val).format('YYYY-MM-DD HH:mm')
    }
  },
  methods: {
    init () {},
    lookDetail (item) {
      this.$router.push({
        name: 'order_detail', params: { id: item.id }
      })
    },
    deliverGoods (item) { // 发货按钮
      this.deliverGoodsVisible = true
      const { id, recipient, logisticsName, phone, address } = item
      this.deliverForm = Object.assign(this.deliverForm, { recipient, logisticsName, phone, address })
      this.deliverForm.orderId = id
    },
    async deliverDialogOk () { // 发货dialog确认
      this.deliverOkLoading = true
      const response = await API.deliverGoods(this.deliverForm)
      this.deliverOkLoading = false
      this.deliverGoodsVisible = false
      const { code } = response
      if (code === 1) {
        this.$message({
          message: '发货成功',
          type: 'success'
        })
        this.needShowInfo = Object.assign({}, this.deliverForm)
        this.$emit('changeOrderStateTxt', '已发货')
        this.$emit('loadData')
        this.resetForm('deliverForm')
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    confirmOneself (item) { // 确认自提按钮
      this.doctorOrRecipientTitle = '自提'
      this.doctorOrPickForm.orderId = item.id
      this.doctorOrPickVis = true
    },
    confirmDoctor (item) { // 确认就医按钮
      this.doctorOrRecipientTitle = '就医'
      this.doctorOrPickForm.orderId = item.id
      this.doctorOrPickVis = true
    },
    async confirmDocOrPickOk (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.docOrPickOkLoading = true
          const response = await API.pickGoods(this.doctorOrPickForm)
          this.docOrPickOkLoading = false
          this.doctorOrPickVis = false
          const { code } = response
          if (code === 1) {
            this.needShowInfo = Object.assign({}, this.doctorOrPickForm)
            this.$message({
              message: `${this.doctorOrRecipientTitle}成功`,
              type: 'success'
            })
            this.$emit('changeOrderStateTxt', `已${this.doctorOrRecipientTitle}`)
            this.resetForm('doctorOrPickForm')
            this.$emit('loadData')
          } else {
            this.$message.error(ErrorConfig[code])
          }
        } else {
          return false
        }
      })
    },
    async timesToConfirmClick (item) {
      this.$emit('activeDataLoading')
      this.beHandlingRow = item
      this.timesToConfirmForm.orderId = item.id
      const { id } = item
      const response = await API.timesToConfirmSpec({ id })
      this.$emit('closeDataLoading')
      const { code, data } = response
      if (code === 1) {
        this.timesToConfirmSpec = data
        this.timesToConfirmVis = true
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    resetForm (formName) { // 重置element ui的表单
      this.$refs[formName].resetFields()
    },
    timesToConfirmOk (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.timesToConfirmLoading = true
          const response = await API.timesToConfirm(this.timesToConfirmForm)
          const { code } = response
          if (code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
            this.timesToConfirmLoading = false
            this.timesToConfirmVis = false
            this.$emit('loadData')
          } else {
            if (code === -1) {
              const { msg } = response
              this.$message.error(msg)
            } else {
              this.$message.error(ErrorConfig[code])
            }
          }
        } else {
          return false
        }
      })
    },
    refundYesClick (item) { // 同意退款按钮
      this.refundDiaVis = true
      this.beHandlingRow = item
      this.refundOkForm.totalprice = item.saleOrderVo.totalprice
      this.refundOkForm.id = item.id
      this.refundOkForm.saleRefundId = item.id
    },
    refundDiaOk (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.refundDiaOkLoading = true
          const response = await API.refundOk(this.refundOkForm)
          this.refundDiaOkLoading = false
          this.refundDiaVis = false
          const { code } = response
          if (code === 1) {
            this.$message({
              message: '已同意退款',
              type: 'success'
            })
            this.$emit('loadData')
          } else {
            if (code === -1) {
              const { msg } = response
              this.$message.error(msg)
            } else {
              this.$message.error(ErrorConfig[code])
            }
          }
        } else {
          return false
        }
      })
    },
    refundNoClick (item) {
      this.$confirm('确认拒绝？')
        .then(async _ => {
          this.$emit('activeDataLoading')
          const response = await API.refundNo({ id: item.id })
          this.$emit('closeDataLoading')
          const { code } = response
          if (code === 1) {
            this.$message({
              message: '拒绝成功',
              type: 'success'
            })
            this.$emit('loadData')
          } else {
            if (code === -1) {
              const { msg } = response
              this.$message.error(msg)
            } else {
              this.$message.error(ErrorConfig[code])
            }
          }
        })
        .catch(_ => {})
    },
    auditHasPay (item) { // 审核已付款
      this.$confirm('审核完成？')
        .then(async _ => {
          this.$emit('activeDataLoading')
          const response = await API.auditOrder({ id: item.id })
          this.$emit('closeDataLoading')
          const { code } = response
          if (code === 1) {
            this.$message({
              message: '审核成功',
              type: 'success'
            })
            this.$emit('loadData')
          } else {
            if (code === -1) {
              const { msg } = response
              this.$message.error(msg)
            } else {
              this.$message.error(ErrorConfig[code])
            }
          }
        })
        .catch(_ => {})
    }
  }
}
</script>
<style scoped lang="scss">
.order_baseInfo {
  div {
    margin-top: 20px;
    span {
      font-size: 14px;
      color: #3B3A42;
      &:nth-child(odd) {
        display: inline-block;
        text-align: right;
        width: 70px;
      }
      &:nth-child(even) {
        margin-right: 40px;
      }
    }
  }
}
</style>
